const fs = require('fs');
const zlib = require('zlib')
const Bitwise = require('../BitwiseBuffer'); //按位运算库
const Path = require("path");
const windows = global.windows;
const Jimp = global.Jimp;
// const { println } = require("../Console");
const println = console.log;

/*
    纹理格式解读

    纹理就是一个像素一个像素存起来，根据不同精度有不同的存储方式

    ARGB_1555=>A1R5G5B5  A透明度 1位  R红色 5位 G绿色 5位 B蓝色 5位 
       存储时只用`16位=2个字节`表示一个像素，需要通过计算还原成成4字节

    ARGB_4444=>A4R4G4B4  同上, 每个像素点16位
       存储时使用`16位=2字节`表示一个像素 需要通过计算还原成成4字节

    ARGB_8888=>A8R8G8B8  同上, 每个像素点32位
       存储时使用`32位=4字节`表示一个元素  存储顺序bgra

    注意 png的像素点数据结构是 RGBA
*/

const exportPngFileA8888 = (config, buffer) => {
    console.log("exportPngFileA8888")
    // console.log("width", config.width)
    // console.log("height", config.height)
    // console.log("w*h=",config.width*config.height)
    // console.log("大小应为 w*h*2=", config.width * config.height * 2)
    // console.log("buffer.length", buffer.length);

    //先将buffer存入array中
    let data = [];
    buffer.forEach(e => {
        data.push(parseInt(e.toString(10)))
    })
    // console.log("data",data.length);

    let out = [];
    for (let i = 0; i < config.height; i++) {
        out[i] = [];

        for (let j = 0; j < config.width; j++) {
            let r = data[i * config.width * 4 + j * 4 + 2]; // red
            let g = data[i * config.width * 4 + j * 4 + 1]; // green
            let b = data[i * config.width * 4 + j * 4 + 0]; // blue
            let a = data[i * config.width * 4 + j * 4 + 3]; // alpha

            out[i][j] = [r, g, b, a];
        }
    }

    // console.log("exportPngFileA8888 计算像素完毕")
    return out;
}

const exportPngFileA4444 = (config, buffer) => {
    console.log("exportPngFileA4444")
    // console.log("width", config.width)
    // console.log("height", config.height)
    // console.log("w*h=",config.width*config.height)
    // console.log("大小应为 w*h*2=", config.width * config.height * 2)
    // console.log("buffer.length", buffer.length);

    //先将buffer存入array中
    let data = [];
    buffer.forEach(e => {
        data.push(parseInt(e.toString(10)))
    })
    // console.log("data",data.length);

    let out = [];

    for (let i = 0; i < config.height; i++) {
        out[i] = [];

        for (let j = 0; j < config.width; j++) {
            let r = (data[i * config.width * 2 + j * 2 + 1] & 0x0f) << 4;   // red  
            let g = ((data[i * config.width * 2 + j * 2 + 0] & 0xf0) >> 4) << 4; // green  
            let b = (data[i * config.width * 2 + j * 2 + 0] & 0x0f) << 4;; // blue  
            let a = ((data[i * config.width * 2 + j * 2 + 1] & 0xf0) >> 4) << 4; // alpha

            out[i][j] = [r, g, b, a];
        }
    }

    // console.log("exportPngFileA4444 计算像素完毕")
    return out;
}

/*
    将Argb1555格式的纹理转换png像素点
    @return array[][]: [y][x]=[r,g,b,a]
*/
const exportPngFileA1555 = (config, buffer) => {
    console.log("exportPngFileA1555")
    // console.log("width", config.width)
    // console.log("height", config.height)
    // console.log("w*h=",config.width*config.height)
    // console.log("大小应为 w*h*2=", config.width * config.height * 2)
    // console.log("buffer.length", buffer.length);

    //先将buffer存入array中
    let data = [];
    buffer.forEach(e => {
        data.push(parseInt(e.toString(10)))
    })
    // console.log("data",data.length);

    let out = [];

    for (let i = 0; i < config.height; i++) {
        out[i] = [];

        for (let j = 0; j < config.width; j++) {
            let r = ((data[i * config.width * 2 + j * 2 + 1] & 127) >> 2) << 3;
            let g = (((data[i * config.width * 2 + j * 2 + 1] & 0x0003) << 3) | ((data[i * config.width * 2 + j * 2] >> 5) & 0x0007)) << 3; // green  
            let b = (data[i * config.width * 2 + j * 2] & 0x003f) << 3; // blue 
            let a = (data[i * config.width * 2 + j * 2 + 1] >> 7) == 0 ? 0 : 255; // alpha

            out[i][j] = [r, g, b, a];
        }
    }

    // console.log("exportPngFileA1555 计算像素完毕")
    return out;
}

const exportPngFile = (config, buffer, pngPath) => {
    // console.log("exportPngFile", config.dwType)

    //创建文件夹
    let dir = Path.dirname(pngPath);
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }


    let datas =
        config.dwType == 14 ? exportPngFileA1555(config, buffer) :
            config.dwType == 15 ? exportPngFileA4444(config, buffer) :
                config.dwType == 16 ? exportPngFileA8888(config, buffer) :
                    null;

    if (!datas) {
        return;
    }


    let image = new Jimp(config.width, config.height, function (err, image) {
        if (err) throw err;

        datas.forEach((row, y) => {
            row.forEach((rgba, x) => {
                let color = Buffer.from(rgba, "hex");
                color = color.toString("hex");
                color = parseInt("0x" + color);
                // console.log("设置Jimp",x,y,color);
                image.setPixelColor(color, x, y);
            });
        });

        //直接输出到文件
        image.writeAsync(pngPath).then(()=>{

        });

        image.write(pngPath, err => {
            if (err) {
                console.log(err);
            }
        })

        //获取base64
        // image.getBase64Async("image/png").then(base64=>{
        //     console.log("base64:",base64);
        // });

        // image.getBase64("image/png",(err,base64)=>{
        //     if(err){
        //         console.log(err)
        //         return;
        //     }

        //     console.log("base64:",base64);
        // });


        //获取输出Buffer
        // image.getBufferAsync("image/png").then(buffer=>{
        //     console.log("buffer:",buffer);
        // });

        // image.getBuffer("image/png",(err,buffer)=>{
        //     if(err){
        //         console.log(err);
        //         return
        //     }
        //     console.log("buffer:",buffer);
        // })
    });
}

const getPngFile = (config, buffer) => new Promise((res, rej) => {
    if (config.dwType == 17 || !buffer || buffer.length == 0) {
        new Jimp(0, 0, function (err, image) {
            res(image);
        });
        return;
    }

    let datas =
        config.dwType == 14 ? exportPngFileA1555(config, buffer) :
            config.dwType == 15 ? exportPngFileA4444(config, buffer) :
                config.dwType == 16 ? exportPngFileA8888(config, buffer) :
                    null;

    if (!datas) {
        console.error(`getPngFile,解析datas失败,${config.index_name}[${config.index}]`)
        rej(new Error("解析datas失败"));
        return;
    }

    new Jimp(config.width, config.height, function (err, image) {
        if (err) throw err;

        datas.forEach((row, y) => {
            row.forEach((rgba, x) => {
                let color = Buffer.from(rgba, "hex");
                color = color.toString("hex");
                color = parseInt("0x" + color);
                // console.log("设置Jimp",x,y,color);
                image.setPixelColor(color, x, y);
            });
        });

        res(image);
    });
})

module.exports = {
    exportPngFile,
    getPngFile,
}